package com.witmed.mine.view.viewmodel

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.witmed.home.view.resp.VideoHistoryRespository
import com.witmed.lib_common.room.VideoHistory
import com.witmed.mine.view.intent.VideoHistroyIntent
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

sealed class VideoHistoryState{
    data class Sucess(var list:List<VideoHistory>):VideoHistoryState()
    data class Error(val msg:String):VideoHistoryState()
    object Loading:VideoHistoryState()
}
class VideoHistoryViewModel:ViewModel() {

    val videoResp by lazy { VideoHistoryRespository() }

    //创建一个意图管道
    val videoChannel= Channel<VideoHistroyIntent>(Channel.UNLIMITED)
    //可变状态的数据流
    private val _videoState= MutableStateFlow<VideoHistoryState>(VideoHistoryState.Loading)
    //可观察的数据流
    val videoState: StateFlow<VideoHistoryState>
        get() = _videoState

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            videoChannel.consumeAsFlow().collect{
                when(it){
                    is VideoHistroyIntent.selectList->
                        videoList(it.context)

                    else->{}
                }
            }
        }
    }

    private fun videoList(context:Context) {
        viewModelScope.launch {
            try {
                videoResp.selectList(context).collect{
                    if(it!=null && it.size!=0){
                        _videoState.value=VideoHistoryState.Sucess(it)
                    }else{
                        _videoState.value=VideoHistoryState.Error("没有数据")
                    }
                }

            }catch (exception:Exception){
                println(exception.stackTrace)
                _videoState.value=VideoHistoryState.Error(exception.message!!)
            }

        }
    }


}